using net_work.Data.DTO.Appr;
using net_work.Data.Enum.Appr;
using NRules.Fluent.Dsl;

namespace net_work.Rules.Appr;

public class ApprovalRuleAll : Rule
{
    public override void Define()
    {
        Name("审批规则：All");

        ApprovalSubmitInfo? submitInfo = null;

        When()
            .Match(() => submitInfo,
                s => s != null && s.SuccessType == NodeSuccessType.All && s.HasHandled == false);

        Then().Do(context => UpdateApprovalSubmitInfo(submitInfo))
            .Do(context => context.Update(submitInfo));
    }

    private static void UpdateApprovalSubmitInfo(ApprovalSubmitInfo? submitInfo)
    {
        if (submitInfo == null)
        {
            return;
        }

        // 快速失败：存在未通过的审批
        if (submitInfo.UnApprovedCount > 0)
        {
            submitInfo.IsSkip = true;
            submitInfo.SkipResult = false;
            submitInfo.HasHandled = true;
            return;
        }

        // 特殊处理：如果是 Teacher 类型，且有一个已通过，则直接跳过
        if (submitInfo.ProcessingType == NodeProcessingType.Teacher)
        {
            submitInfo.IsSkip = true;
            submitInfo.SkipResult = submitInfo.ApprovedCount >= 1;
            submitInfo.HasHandled = true;
            return;
        }
        
        if (submitInfo.ApprovedCount < submitInfo.TaskTotalCount)
        {
            submitInfo.HasHandled = true;
            return;
        }

        submitInfo.IsSkip = true;
        submitInfo.SkipResult = true;
        submitInfo.HasHandled = true;
    }
}